<?php

namespace App\Service;
use Hyperf\DbConnection\Db;
use Hyperf\Cache\Annotation\Cacheable;
use Hyperf\Cache\Annotation\CachePut;
use function Symfony\Component\Translation\t;

class UserService extends CommicService
{
    public function index($res,$applet_id)
    {
        co(function () use ($res,$applet_id) {
            $redis_key = "user_msg:".$applet_id;
            # 查询用户注册
            $this->redisService->rPush($redis_key,json_encode($res));
        });
    }
    public function indexs($res,$applet_id)
    {
        co(function () use ($res,$applet_id) {
            $redis_key = "user_msgsss:".$applet_id;
            # 查询用户注册
            //$this->redisService->rPush($redis_key,json_encode($res));
        });
    }
    #获取头像等信息
//    #[Cacheable(prefix: "user:userinfo:", ttl: 9000)]
    public function user_info(string $applet_id,int $user_id)
    {
        $table_name = "data_user_".$applet_id;
        $where = [
            ['id', '=', $user_id],
        ];
        $user_info = Db::table($table_name)->where($where)->first();
        if (!empty($user_info->id)){
            if (empty($user_info->headimg)){
                $get_sys_config_info = $this->get_sys_config();
                $user_info->headimg = $this->get_curl_tool($get_sys_config_info["user_default_headimg"]);
                if ($user_info->vip_effective_time > 0){
                    $user_info->vip_effective_time_time = strtotime($user_info->vip_effective_time);
                }else{
                    $user_info->vip_effective_time_time = 0;
                }
            }
        }
        return $user_info;
    }

//    #[CachePut(prefix: "user:userinfo:", ttl: 9000)]
    public function update_user_info(string $applet_id,int $user_id){
        $table_name = "data_user_".$applet_id;
        $where = [
            ['id', '=', $user_id],
        ];

        $user_info = Db::table($table_name)->where($where)->first();
        if (!empty($user_info->id)){
            if (empty($user_info->headimg)){
                $get_sys_config_info = $this->get_sys_config();
                $user_info->headimg = $this->get_curl_tool($get_sys_config_info["user_default_headimg"]);
                if ($user_info->vip_effective_time > 0){
                    $user_info->vip_effective_time_time = strtotime($user_info->vip_effective_time);
                }else{
                    $user_info->vip_effective_time_time = 0;
                }
            }
        }
        return $user_info;
    }

    public function Inc_coin(string $applet_id,int $user_id,$data){
        echo "更新用户数据".PHP_EOL;
        $table_name = "data_user_".$applet_id;
        $user_info = $this->user_info($applet_id,$user_id);
        if (!empty($data["give_coin"])){
            $update["give_coin"] = (int)$user_info->give_coin + $data["give_coin"];
        }
        if (!empty($data["ml_coin"])){
            $update["ml_coin"] = (int)$user_info->ml_coin + $data["ml_coin"];
        }
        echo "更新数据".PHP_EOL;
        print_r($update).PHP_EOL;
        if (!empty($update)){
            Db::table($table_name)->where([
                "id"=>$user_id
            ])->update($update);
            $this->update_user_info($applet_id,$user_id);
        }
    }
    #通过open_id获取用户信息
    public function get_xc_open_id_info(string $applet_id,string $xc_open_id){
        //$redis_key = "user_openid_user_id:".$applet_id;
        $redis_key = "user_openid_user_id:".$applet_id.':'.$xc_open_id;
        $table_name = "data_user_".$applet_id;
        //$user_info = $this->redisService->hGet($redis_key,$xc_open_id);
        $user_info = $this->redisService->get($redis_key);
        $user_info = json_decode($user_info,true);
//        $user_info= [];
        if (empty($user_info)){
            $where = [
                "xc_open_id" => $xc_open_id,
            ];
            $user_info = Db::table($table_name)->where($where)->select('id','username',"headimg","applet_id","xc_open_id","merchant_id","spread_id",'ip')->first();
            $user_info = $this->object_to_find_array($user_info);
            if ($user_info){
                //2024/5/6 修改key定时三天
                $this->redisService->setex($redis_key,259200,json_encode($user_info));
                //$this->redisService->hSet($redis_key,$xc_open_id,json_encode($user_info));
            }
        }
        return $user_info;
    }

    public function  addRefluxLog($data){
        $id = Db::table('reflux_user_log')->insert($data);

    }
    public function addUser($data){
        # 新用户
        $table_name = "data_user_".$data["applet_id"];
        $applet_info = $this->get_applet_info($data["applet_id"]);
        $data["merchant_id"] = $applet_info["merchant_id"];

        $user_id = Db::table($table_name)->insertGetId($data);
        echo "注册用户ID".$user_id.PHP_EOL;
        if ($user_id){
            $redis_key = "user_openid_user_id:".$data["applet_id"];
            $data["id"] = $user_id;
            $data["headimg"] = $applet_info["user_default_headimg"];
            $data["username"] = '';
            //$this->redisService->hSet($redis_key,$data["xc_open_id"],json_encode($data));

            //2024/5/6 修改key定时三天
            $redis_key = "user_openid_user_id:".$data["applet_id"].':'.$data["xc_open_id"];
            $this->redisService->setex($redis_key,259200,json_encode($data));
        }
        return $user_id;
    }
    public function updateUser($applet_id,$xc_open_id,$data){
        $table_name = "data_user_".$applet_id;
        $applet_info = $this->get_applet_info($applet_id);


        if(!$applet_info) {
            return '';
        }
        $rec = $this->get_xc_open_id_info($applet_id,$xc_open_id);
        Db::table($table_name)->where('xc_open_id','=',$xc_open_id)->update($data);
        $rec['spread_id'] = $data['spread_id'];

//        $redis_key = "user_openid_user_id:".$applet_id;
//        $this->redisService->hSet($redis_key,$xc_open_id,json_encode($rec));

        //2024/5/6 修改key定时三天
        $redis_key = "user_openid_user_id:".$applet_id.':'.$xc_open_id;
        $this->redisService->setex($redis_key,259200,json_encode($rec));
    }
    public function get_last_order($applet_id,$user_id,$spread_id){
        $payment = DB::table('data_payment')
            ->where([
                'user_id'=>$user_id,
                'applet_id'=>$applet_id,
                'spread_id'=>$spread_id,
                'status' =>2
                ])
            ->orderBy('id','desc')
            ->first();
        $payment = $this->object_to_find_array($payment);
        if(empty($payment)) {
            return '';
        } else {
            return $payment;
        }
    }



    public function get_wx_openid(string $applet_id,$jscode,$platform_type,$status=0){
        $applet_info = $this->get_applet_info($applet_id);
        if ($status==0){
            $url_url ="https://api.weixin.qq.com/sns/jscode2session?appid={$applet_info['app_id']}&secret={$applet_info['app_secret']}&grant_type=authorization_code&js_code={$jscode}";
            $response = $this->httpclient->request('GET', $url_url);
            $content = $response->getBody()->getContents();
            $res = json_decode($content,true);
//            var_dump($res);
            if(isset($res['session_key'])) {
                $key = 'login_info:'.$applet_id;
                $res['platform_type'] = $platform_type;
                $this->redisService->hSet($key,$res['openid'],json_encode($res));
            }
            return json_decode($content,true);
        }else{
            return [
                "openid"=>"texta".$applet_id.mt_rand(100000,999999),
                "session_key"=>"test"
            ];
        }

    }
    public function ios_payment($applet_id,$xc_open_id) {
        $key = 'login_info:'.$applet_id;
        $res = $this->redisService->hGet($key,$xc_open_id);
        $res = json_decode($res,true);
        if (!$res) {
            return false;
        } else {
            $data['ios_payment'] = 1;
            $table_name = "data_user_".$applet_id;
            Db::table($table_name)->where('xc_open_id','=',$xc_open_id)->update($data);
            return true;
//            if($res['platform_type'] == 'ios') {
//                $data['ios_payment'] = 1;
//                $table_name = "data_user_".$data["applet_id"];
//                Db::table($table_name)->where('xc_open_id','=',$xc_open_id)->update($data);
//                return true;
//            } else {
//                return true;
//            }

        }
    }

    public function get_user_applet_info(string $applet_id){
        return $this->get_applet_info($applet_id);
    }
    public function recharge_log($applet_id,$user_id,$page){
        # 充值记录
        #"user_id"=>$user_id,
        $list = Db::table("data_user_log")->where(["applet_id"=>$applet_id,"user_id"=>$user_id,"stype"=>1])->select("id","name","ml_coin","stype","create_at","recharge_type","give_coin","amount")->forPage($page)->orderBy("create_at","desc")->get();
        $list = $this->object_to_array($list);
        foreach ($list as $key=>$value) {
            $list[$key]['amount'] = $value['amount'] /100;
        }
        return $list;
    }

    #抖音部份
    public function get_dy_openid(string $applet_id,$jscode,$status=0){
        $applet_info = $this->get_applet_info($applet_id);
        if ($status==0){
            $url_url ="https://developer.toutiao.com/api/apps/v2/jscode2session";
            $postData = [
                'appid' =>$applet_info['app_id'],
                'secret' =>$applet_info['app_secret'],
                'code' =>$jscode
            ];

            $headers = [
                'Content-Type' => 'application/json',
            ];
            $response = $this->httpclient->post($url_url, [
                'headers' => $headers,
                'json' => $postData,
            ]);
            $content = $response->getBody()->getContents();
            $res = json_decode($content,true);
            var_dump($res);
            return $res['data'];
//            return json_decode($content,true);
        }else{
            return [
                "openid"=>"texta".$applet_id.mt_rand(100000,999999),
                "session_key"=>"test"
            ];
        }
    }
    public function error_info($applet_id,$error_info,$xc_open_id,$errorcode=0) {
        Db::table('error_info')->insert([
            'error_info'=>json_encode($error_info),
            'xc_open_id'=>$xc_open_id,
            'applet_id'=>$applet_id,
            'errorcode'=> $errorcode,
            'create_time'=>date('Y-m-d H:i:s',time())
        ]);
        return true;
    }

    //消耗代币列表
    public function consumption_list($applet_id,$user_id,$page){
        # 消耗代币列表
        $list = Db::table("data_user_pay_playlet_log")
            ->where(["applet_id"=>$applet_id,"user_id"=>$user_id,"tpye"=>1])
            ->where('data_user_pay_playlet_log.amount','>',0)
            ->leftJoin('playlet','playlet.id','=','data_user_pay_playlet_log.playlet_id')
            ->select("data_user_pay_playlet_log.id","playlet.name","data_user_pay_playlet_log.create_at","data_user_pay_playlet_log.playlet_number","data_user_pay_playlet_log.amount")
            ->forPage($page)
            ->orderBy("data_user_pay_playlet_log.create_at","desc")->get();
        $list = $this->object_to_array($list);
        return $list;
    }
}